package com.shw.loco.adapter;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.shw.loco.adapter.LocoMainService.SHWMainBinder;
import com.shw.loco.util.InfoUtils;
import com.shw.loco.vo.ComPortInfo;

/**
 * 
 * @author HAHA
 * 
 */
public class LocoNetManager {

	// private ExecutorService executorService =
	// Executors.newCachedThreadPool();
	private static final String TAG = "LocoNetManager";
	private SharedPreferences sharedPreferences;
	private Socket clientSocket;
	// private BufferedWriter bufferedWriter = null;
	// private BufferedReader bufferedReader = null;
	private InputStream inputStream = null;
	private OutputStream outputStream = null;
	public static Vector<byte[]> vector = new Vector<byte[]>();
	private Context context;
	private boolean flag = true;
	private String ip_info;
	private String ip_port;
	private int netDelay = 400;
	private int heartDelay=100000;

	public LocoNetManager(Context context, SharedPreferences sharedPreferences) {
		this.context = context;
		this.sharedPreferences = sharedPreferences;
		try {
			ip_info = sharedPreferences.getString(InfoUtils.IP_INFO, "");
			if (ip_info == null || ip_info.length() < 1)
				throw new Exception("ip_info exception");
		} catch (Exception e) {
			ip_info = InfoUtils.SERVER_IP;
		}
		try {
			InfoUtils.TERMINALID = sharedPreferences.getString(InfoUtils.LOCOTERMINAL, "0000");
			if (!InfoUtils.TERMINALID.equals("0") || InfoUtils.TERMINALID.length() < 1)
				throw new Exception("rfid_port exception");
		} catch (Exception e) {
			InfoUtils.TERMINALID = "0000";
		}
		try {
			ip_port = sharedPreferences.getString(InfoUtils.IP_PORT, "");
			if (ip_port == null || ip_port.length() < 1)
				throw new Exception("ip_info exception");
		} catch (Exception e) {
			ip_port = InfoUtils.SERVER_PORT;
		}
		try {
			netDelay = Integer.valueOf(sharedPreferences.getString(
					InfoUtils.CENTER_TIME, "400"));
			if (netDelay <= 0 )
				throw new Exception("netDelay exception");
		} catch (Exception e) {
			netDelay = 400;
		}
		try {
			heartDelay = Integer.valueOf(sharedPreferences.getString(
					InfoUtils.HEART_TIME, "100000"));
			if (heartDelay <= 0)
				throw new Exception("heartDelay exception");
		} catch (Exception e) {
			heartDelay = 100000;
		}
	}

	public LocoNetManager(SharedPreferences sharedPreferences) {
		this.sharedPreferences = sharedPreferences;
		try {
			ip_info = sharedPreferences.getString(InfoUtils.IP_INFO, "");
			if (ip_info == null || ip_info.length() < 1)
				throw new Exception("ip_info exception");
		} catch (Exception e) {
			ip_info = InfoUtils.SERVER_IP;
		}
		try {
			InfoUtils.TERMINALID = sharedPreferences.getString(InfoUtils.LOCOTERMINAL, "0000");
			if (!InfoUtils.TERMINALID.equals("0") || InfoUtils.TERMINALID.length() < 1)
				throw new Exception("rfid_port exception");
		} catch (Exception e) {
			InfoUtils.TERMINALID = "0000";
		}
		try {
			ip_port = sharedPreferences.getString(InfoUtils.IP_PORT, "");
			if (ip_port == null || ip_port.length() < 1)
				throw new Exception("ip_info exception");
		} catch (Exception e) {
			ip_port = InfoUtils.SERVER_PORT;
		}
		try {
			netDelay = Integer.valueOf(sharedPreferences.getString(
					InfoUtils.CENTER_TIME, "400"));
			if (netDelay <= 400 )
				throw new Exception("netDelay exception");
		} catch (Exception e) {
			netDelay = 400;
		}
		try {
			heartDelay = Integer.valueOf(sharedPreferences.getString(
					InfoUtils.HEART_TIME, "100000"));
			if (heartDelay <= 100000)
				throw new Exception("heartDelay exception");
		} catch (Exception e) {
			heartDelay = 100000;
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				getConnect();
				startSendRevThread();
				break;
			default:
				break;
			}

		}

	};

	private void getConnect() {
		try {
			LocoMainTrigger.openConnect(context);
			clientSocket = new Socket();
			clientSocket.connect(
					new InetSocketAddress(ip_info, Integer.valueOf(ip_port)),
					5000);
			// bufferedWriter = new BufferedWriter(new OutputStreamWriter(
			// clientSocket.getOutputStream()));
			// bufferedReader = new BufferedReader(new InputStreamReader(
			// clientSocket.getInputStream()));
			inputStream = clientSocket.getInputStream();
			outputStream = clientSocket.getOutputStream();
		} catch (Exception e) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e1) {
				// e1.printStackTrace();
			}
			getConnect();
		}
	}

	public void offConnect() {
		try {
			// bufferedReader.close();
			// bufferedReader = null;
			// bufferedWriter.close();
			// bufferedWriter = null;
			if (inputStream != null) {
				inputStream.close();
				inputStream = null;
			}
			if (outputStream != null) {
				outputStream.close();
				outputStream = null;
			}
			if (clientSocket != null) {
				clientSocket.close();
				clientSocket = null;
			}
		} catch (Exception e1) {
		}
	}

	public void isConnected() {
		try {
			clientSocket.sendUrgentData(0xff);
		} catch (Exception e) {
			getConnect();
		}
	}

	private SHWSendThread sendThread;
	private SHWRecThread recThread;
	private SHWHeartThread heartThread;
	public void startSendRevThread() {
		sendThread = new SHWSendThread();
		sendThread.start();
		heartThread = new SHWHeartThread();
		heartThread.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		recThread = new SHWRecThread();
		recThread.start();
	}

	public void stopSendRevThread() {
		/*
		 * Thread sendThreads=Thread.currentThread(); while (sendThreads ==
		 * sendThread) { try { sendThreads.interrupt(); } catch (Exception e){
		 * throw new RuntimeException("Interrupted",e); } } Thread
		 * recThreads=Thread.currentThread(); while (recThreads == recThread) {
		 * try { recThreads.interrupt(); } catch (Exception e){ throw new
		 * RuntimeException("Interrupted",e); } }
		 */
		if (recThread != null){
			recThread.stop=true;
			recThread.interrupt();}
		if (heartThread !=null){
			heartThread.stop=true;
			heartThread.interrupt();
		}
		if (sendThread != null){
			sendThread.stop=true;
			sendThread.interrupt();}
		offConnect();
	}

	class SHWRecThread extends Thread {

		public boolean stop=false;
		
		public SHWRecThread() {

		}

		@Override
		public void run() {
			if(!stop){
			Log.d(TAG, "start  接受线程");
			int size = 0;
			
			while (!stop) {
				try {
//					Log.d(TAG, "接受线程");
					byte[] buffer = new byte[2048];
					size = 0;
					while (inputStream.available() > 0) {
						size = inputStream.read(buffer);
					}
					if (size > 0) {
						ComPortInfo ComRecData = new ComPortInfo("3g", buffer,
								size, 3,context);
						if (context != null)
							LocoInfoQueue.addComQueue(ComRecData);
					}
				} catch (Exception e) {
					Log.d(TAG, "接受线程网路偶异常");
				}
				try {
					sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			}
		}

	}

	class SHWHeartThread extends Thread{
		public boolean stop=false;
		public SHWHeartThread() {

		}
		
		@Override
		public void run() {
			while(!stop){
				try {
					if(LocoInfoQueue.resultToCenterVector.size()<2)
					LocoInfoQueue.resultToCenterVector.add(InfoUtils.HexToByteArr("67"+InfoUtils.leftAdding( InfoUtils.TERMINALID,"0", 4)+"0A00"
							+ InfoUtils.CRC_16(InfoUtils
									.HexToByteArr("67"+InfoUtils.leftAdding( InfoUtils.TERMINALID,"0", 4)+"0A00"))));
					Thread.sleep(heartDelay);
				} catch (Exception e) {

				}
			}}
	}
	
	class SHWSendThread extends Thread {
		public boolean stop=false;
		public SHWSendThread() {

		}

		@Override
		public void run() {
			if(!stop){
			getConnect();
//			Log.d(TAG, "start  发送线程");

			while (!stop) {
				try {
					if (LocoInfoQueue.resultToCenterVector.size() > 0) {
						//长时间未连通，将历史数据删除
//						if (LocoInfoQueue.resultToCenterVector.size() > 10) {
//							for (int i = 0; i < (LocoInfoQueue.resultToCenterVector
//									.size() - 1); i++) {
//								LocoInfoQueue.resultToCenterVector.remove(i);
//							}
//						}
						outputStream.write(LocoInfoQueue.resultToCenterVector
								.remove(0));
						outputStream.flush();
					} 
					Log.d(TAG, "发送线程");
				} catch (Exception e) {
					Log.d(TAG, "发送线程网络异常");
					// offConnect();
					getConnect();
				}
				try {
					sleep(netDelay);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}}
	}

}
